#include "GY_QtTimer.h"

GY_QtTimer::GY_QtTimer(QObject *parent):QObject(parent)
{
    m_CurrentTime=0;
    m_CurrentDate=QDate(2000,1,1);
    m_TimeSpeed=1;
    m_TimeInter=1000000;
    connect(&m_Timer,&QTimer::timeout,this,&GY_QtTimer::timeOutEvent);
}
/**
 * @brief getCurrentTime 获取当前时间
 * @return 返回当前计时时间
 */
quint64 GY_QtTimer::getCurrentTime()
{
    quint64 time=0;
    m_TimeMutex.lock();
    time=m_CurrentTime;
    m_TimeMutex.unlock();
    return time;
}
/**
 * @brief setCurrentTime 设置当前时间
 * @param time 当前时间
 */
void GY_QtTimer::setCurrentTime(const quint64 time)
{
    //判定如果输入的时间超过24小时视为无效
    if(time>ONE_DATE_MICROSECOND)
    {
        return;
    }
    m_TimeMutex.lock();
    m_CurrentTime=time;
    m_TimeMutex.unlock();
}
/**
 * @brief getCurrentDate  获取当前日期
 * @return 返回日期
 */
QDate GY_QtTimer::getCurrentDate()
{
    QDate date;
    m_DateMutex.lock();
    date=m_CurrentDate;
    m_DateMutex.unlock();
    return date;
}
/**
 * @brief setCurrentDate 设置当前日期
 * @param date 日期
 */
void GY_QtTimer::setCurrentDate(const QDate & date)
{
    m_DateMutex.lock();
    m_CurrentDate=date;
    m_DateMutex.unlock();
}
/**
 * @brief timeOut 时间间隔事件
 */
void GY_QtTimer::timeOutEvent()
{
    m_TimeMutex.lock();
    m_CurrentTime+=m_TimeInter*m_TimeSpeed;
    m_TimeMutex.unlock();
    qint64 time=m_CurrentTime;
    m_DateMutex.lock();
    QDate date=m_CurrentDate;
    m_DateMutex.unlock();
    //如果时间大于一天微秒数说明到了第二天
    if(time>=ONE_DATE_MICROSECOND)
    {
        time-=ONE_DATE_MICROSECOND;
        m_TimeMutex.lock();
        m_CurrentTime=time;
        m_TimeMutex.unlock();
        qint64 addDay=1;
        date=date.addDays(addDay);
        m_DateMutex.lock();
        m_CurrentDate=date;
        m_DateMutex.unlock();
    }
    //如果时间小于0说明回到了上一天
    else if(time<0)
    {
        time+=ONE_DATE_MICROSECOND;
        m_TimeMutex.lock();
        m_CurrentTime=time;
        m_TimeMutex.unlock();
        qint64 addDay=-1;
        date=date.addDays(addDay);
        m_DateMutex.lock();
        m_CurrentDate=date;
        m_DateMutex.unlock();
    }
    emit timeOutSiganl(date,time);
}
/**
 * @brief startTimer 开始计时
 * @param timeInter 计时器间隔
 */
void GY_QtTimer::startTimer(const qint32 timeInter)
{
    if(m_Timer.isActive())
    {
        return;
    }
    m_TimeInter=timeInter;
    m_Timer.start(m_TimeInter/1000);
}
/**
 * @brief stopTimer
 * 停止计时器
 */
void  GY_QtTimer::stopTimer()
{
    if(!m_Timer.isActive())
    {
        return;
    }
    m_Timer.stop();
}
/**
 * @brief setTimerSpeed  设置计时器速率
 * @param timeSpeed 计时速率(倒放时为false)
 */
void GY_QtTimer::setTimerSpeed(const double timeSpeed)
{
    m_TimeMutex.lock();
    m_TimeSpeed=timeSpeed;
    m_TimeMutex.unlock();
}
